<template>
  <view class="page">
    <nav-bar title="订单详情" class="nav-bar" />
    <block v-if="orderData">
      <view class="store">
        <view>{{ orderData.storeName }}</view>
        <view class="addres">{{ orderData.storeAddress }}</view>
      </view>
      <view class="merch">
        <view class="rig">
          <view class="top"
            ><view class="indus">{{
              ORDER_DELIVER_METHOD_TEXT[orderData.type]
            }}</view></view
          >
          <view class="btm" v-if="orderData.appointmentTime"
            >预计{{
              orderData.type === ORDER_DELIVER_METHOD.PUB_SELF_PICKUP
                ? "自提"
                : "送达"
            }}时间：{{ orderData.appointmentTime }}</view
          >
        </view>
        <view class="lef">
          <view>
            <order-status
              :status="orderData.orderStatus"
              :deliveryString="orderData.type"
              :subStatusInt="orderData.subStatusInt"
              :isHasRefund="
                orderData.orderStatus === ORDER_STATUS.CANCEL &&
                orderData.paymentTime
              "
            />
          </view>
          <view class="cause" v-if="orderData.remark">{{
            orderData.remark
          }}</view>
        </view>
      </view>
      <view class="user-info">
        <view class="place-order">
          <view>
            下单人：{{ orderData.customerName }}
            <text>{{ orderData.memberPhone }}</text>
          </view>
          <view @click="makeCall(orderData.memberPhone)" class="phone"
            ><view class="iconfont icon-dianhua1"></view
          ></view>
        </view>
        <view
          class="rec-order"
          v-if="orderData.type === ORDER_DELIVER_METHOD.PUB_LOCAL"
        >
          <view>
            <view>
              收货人：{{ orderData.delivery.userName }}
              <text>{{ orderData.delivery.phone }}</text>
            </view>
            <view class="row"
              >{{ orderData.delivery.province }}{{ orderData.delivery.city
              }}{{ orderData.delivery.country }}{{ orderData.delivery.street
              }}{{ orderData.delivery.detail }}</view
            >
            <!--            <view class="row remarks">备注：{{ orderData.userRemark }}</view>-->
          </view>
          <view @click="makeCall(orderData.delivery.phone)" class="phone"
            ><view class="iconfont icon-dianhua1"></view
          ></view>
        </view>
        <view class="userRemark">
          <view class="row remarks"
            >备注：{{ orderData.userRemark || "" }}</view
          >
        </view>
      </view>
      <view class="shop-info">
        <u-line></u-line>
        <u-read-more
          showHeight="460rpx"
          toggle
          closeText="展开全部商品"
          :color="themeColor"
          textIndent=""
        >
          <view
            class="shop-box"
            v-for="good in orderData.items"
            :key="good.goodsId"
          >
            <view class="lef">
              <view class="img"
                ><image
                  :src="ossBaseUrl + good.coverImg"
                  mode="aspectFill"
                ></image
              ></view>
              <view class="flex1">
                <view class="name">{{ good.title }}</view>
                <view class="spec" v-if="good.skuInfo">{{
                  good.skuInfo | formatGood
                }}</view>
              </view>
            </view>
            <view class="rig">
              <view class="num">x{{ good.num }}</view>
              <view class="price">
                ￥
                <text class="bigPrice">{{
                  good.price | formatMoneyStart
                }}</text>
                <text>{{ good.price | formatMoneyLast }}</text>
              </view>
            </view>
          </view>
        </u-read-more>
      </view>
      <view class="amount-info">
        <view class="row">
          <view class="tit">商品小计</view>
          <view>￥{{ orderData.totalFee | formatCurrency }}</view>
        </view>
        <view
          class="row"
          v-if="orderData.type === ORDER_DELIVER_METHOD.PUB_PACK"
        >
          <view class="tit">打包费</view>
          <view>￥{{ orderData.packFee | formatCurrency }}</view>
        </view>

        <view
          class="row"
          v-if="orderData.type === ORDER_DELIVER_METHOD.PUB_SELF_PICKUP"
        >
          <view class="tit">包装费</view>
          <view>￥{{ orderData.packFee | formatCurrency }}</view>
        </view>

        <view
          class="row"
          v-if="orderData.type === ORDER_DELIVER_METHOD.PUB_LOCAL"
        >
          <view class="tit">配送费</view>
          <view>￥{{ orderData.deliveryFee | formatCurrency }}</view>
        </view>
        <view class="row">
          <view class="tit">优惠</view>
          <view class="yh">
            <view>-￥{{ orderData.allDiscountFee | formatCurrency }}</view>
            <view v-if="orderData.discountAmount.type">{{
              orderData.discountAmount.remark
            }}</view>
          </view>
        </view>
      </view>
      <view class="order-info">
        <view class="row">
          <view class="tit">订单编号</view>
          <view>{{ orderData.orderNo }}</view>
        </view>
        <view class="row">
          <view class="tit">下单时间</view>
          <view>{{ orderData.createTime || "" }}</view>
        </view>
        <view class="row" v-if="orderData.paymentTime">
          <view class="tit">支付时间</view>
          <view>{{ orderData.paymentTime }}</view>
        </view>
        <view
          class="row"
          v-if="
            orderData.orderStatus !== ORDER_STATUS.WAITING &&
            orderData.orderStatus === ORDER_STATUS.CANCEL &&
            orderData.paymentTime
          "
        >
          <view class="tit">支付方式</view>
          <view>{{ orderData.payInfo.paymentName || "" }}</view>
        </view>
        <block v-if="orderData.type === ORDER_DELIVER_METHOD.PUB_LOCAL">
          <view class="row" v-if="orderData.delivery.deliveryTime">
            <view class="tit">配送时间</view>
            <view>{{ orderData.delivery.deliveryTime || "" }}</view>
          </view>
        </block>
        <view class="row" v-if="orderData.finishTime">
          <view class="tit">完成时间</view>
          <view>{{ orderData.finishTime || "" }}</view>
        </view>
        <view class="row" v-if="orderData.cancelTime">
          <view class="tit"
            >{{
              orderData.orderStatus === ORDER_STATUS.CANCEL &&
              orderData.paymentTime
                ? "退款"
                : "取消"
            }}时间</view
          >
          <view>{{ orderData.cancelTime || "" }}</view>
        </view>
      </view>

      <view class="blank-box"></view>

      <view class="oper-info">
        <view class="amount">
          <block>
            <text
              v-if="
                orderData.orderStatus === ORDER_STATUS.WAITING ||
                (orderData.orderStatus === ORDER_STATUS.CANCEL &&
                  !orderData.paymentTime)
              "
              >应收</text
            >
            <text v-else>实收</text>
          </block>
          ：<view class="money"
            >￥<text>{{ orderData.payInfo.payFee | formatMoneyStart }}</text
            >{{ orderData.payInfo.payFee | formatMoneyLast }}</view
          ></view
        >

        <view class="flexAIC">
          <view
            class="print operBtn"
            @click="handlePrint"
            v-if="
              orderData.orderStatus !== ORDER_STATUS.CANCEL &&
              orderData.orderStatus !== ORDER_STATUS.WAITING
            "
          >
            <view class="iconfont icon-24px"></view>
            <view>打印小票</view>
          </view>

          <view
            class="operBtn"
            v-if="
              orderData.orderStatus === ORDER_STATUS.UNDERWAY ||
              orderData.orderStatus === ORDER_STATUS.FINISH
            "
          >
            <u-button
              @click="handleRefund"
              type="primary"
              :plain="true"
              :customStyle="cusButton"
              text="退款"
            ></u-button>
          </view>

          <block v-if="orderData.type === ORDER_DELIVER_METHOD.PUB_LOCAL">
            <view
              class="operBtn"
              v-if="
                orderData.orderStatus === ORDER_STATUS.UNDERWAY &&
                orderData.subStatusInt === ORDER_PUB_LOCAL_STATUS.WAITING_SEND
              "
              ><u-button
                @click="handleDelivery"
                type="primary"
                :customStyle="cusButton"
                text="配送"
              ></u-button>
            </view>
            <view
              class="operBtn"
              v-if="
                orderData.orderStatus === ORDER_STATUS.UNDERWAY &&
                orderData.subStatusInt === ORDER_PUB_LOCAL_STATUS.SENDING
              "
            >
              <u-button
                @click="handleFinishSendingOrder"
                :customStyle="cusButton"
                type="primary"
                text="送达"
                >送达</u-button
              >
            </view>
          </block>

          <block v-else>
            <view
              class="operBtn"
              v-if="orderData.orderStatus === ORDER_STATUS.UNDERWAY"
            >
              <u-button
                @click="handleWriteOff"
                type="primary"
                :customStyle="cusButton"
                text="核销"
              ></u-button>
            </view>
          </block>
        </view>
      </view>
    </block>
  </view>
</template>

<script>
import {
  orderDelivered,
  orderDelivery,
  orderDetail,
  orderPrint,
  orderRefund,
} from "@/service/api/sp-order";
import {
  ORDER_DELIVER_METHOD,
  ORDER_DELIVER_METHOD_TEXT,
  ORDER_PUB_LOCAL_STATUS,
  ORDER_STATUS,
  ORDER_STATUS_TEXT,
} from "@/pages/sp-order/const/order";
import { mapState } from "@dcloudio/vue-cli-plugin-uni/packages/vuex3/dist/vuex.common";
import { pubEquipList } from "@/service/api/sp-equi";
import orderStatus from "../../components/orderStatus";

export default {
  components: { orderStatus },
  data() {
    return {
      ORDER_PUB_LOCAL_STATUS,
      ORDER_STATUS,
      ORDER_STATUS_TEXT,
      ORDER_DELIVER_METHOD,
      ORDER_DELIVER_METHOD_TEXT,
      ossBaseUrl: process.env.VUE_APP_BASE_FileUrl,
      cusButton: {
        width: "120rpx", //驼峰命名注意
        height: "70rpx",
      },
      options: {},
      orderData: null,
    };
  },
  filters: {
    formatGood(val) {
      return JSON.parse(val).join("/");
    },

    formatMoneyStart(e) {
      return String(e / 100).split(".")[0] + ".";
    },
    formatMoneyLast(e) {
      return String(e / 100).split(".")[1] || "00";
    },
  },
  computed: {
    ...mapState("sp-common/auth", ["pubUserInfo"]),
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
  },
  onLoad(options) {
    this.options = options;
    this.fetchOrderDetail();
    this.getEventChannel();
  },
  methods: {
    getEventChannel() {
      const eventChannel = this.getOpenerEventChannel();
      if (JSON.stringify(eventChannel) !== "{}") {
        eventChannel.on("orderList", (res) => {
          this.eventChannelOptions = res;
        });
      }
    },
    async fetchOrderDetail() {
      const res = await orderDetail({ orderNo: this.options.orderCode });
      if (res) {
        this.orderData = res;

        const eventChannel = this.getOpenerEventChannel();
        eventChannel?.emit("orderStatus", {
          orderNo: res.orderNo,
          orderStatus: res.orderStatus,
        });
      }
    },
    // 拨打电话
    makeCall(phone) {
      uni.makePhoneCall({
        phoneNumber: phone,
      });
    },
    async handlePrint() {
      const params = {
        pageNum: 1,
        pageSize: 10,
        equipType: 0,
      };
      if (!this.pubUserInfo?.mainShopStatus) {
        params.pubDomainShopId = this.pubUserInfo.pubDomainShopVo?.id;
      }
      const res = await pubEquipList({
        ...params,
      });
      if (res?.list?.length > 0) {
        uni.showModal({
          title: "提示",
          content: "是否重新打印小票？",
          confirmText: "是",
          cancelText: "否",
          success: async (res) => {
            if (res.confirm) {
              const res = await orderPrint({ orderNo: this.orderData.orderNo });
              if (res?.code === 0) {
                uni.showToast({
                  icon: "success",
                  title: "打印成功",
                });
              }
            }
          },
        });
      } else {
        uni.showToast({
          icon: "error",
          title: "未绑定打印机",
        });
      }
    },
    //退款
    async handleRefund() {
      uni.showModal({
        content: "是否退款？",
        confirmColor: this.$theme.themeColor.primary,
        success: async (modalRes) => {
          if (modalRes.confirm) {
            const orderNo = this.orderData?.orderNo;
            const res = await orderRefund({ orderNo }).catch((err) => {
              uni.showToast({
                title: err.msg,
                icon: "none",
              });
            });
            if (res?.code === 0) {
              uni.showToast({
                title: "退款成功",
                icon: "success",
              });
              await this.fetchOrderDetail();
            }
          }
        },
      });
    },

    //核销
    async handleWriteOff() {
      const {
        orderNo,
        delivery: { takeNo },
      } = this.orderData;
      uni.navigateTo({
        url: `pages/scan/index?type=pubUserWriteOff&takeNo=${takeNo}`,
        events: {
          orderStatus: () => {
            this.fetchOrderDetail().then(() => {
              uni.showToast({
                title: "核销成功",
                icon: "success",
              });
            });
          },
        },
        success: (res) => {
          res.eventChannel.emit("writeOff", {
            orderNo,
          });
        },
      });
      // this.$Router.push({
      //   name: "scan",
      //   params: {
      //     type: "pubUserWriteOff",
      //     takeNo,
      //   },
      // });
      //需要扫公域用户小程序的二维码进行核销
    },
    //去配送
    async handleDelivery() {
      const orderNo = this.orderData?.orderNo;
      const res = await orderDelivery({
        orderNo,
      }).catch((err) => {
        uni.showToast({
          title: err.msg,
          icon: "none",
        });
      });
      await this.fetchOrderDetail();
      if (res?.code === 0) {
        uni.showToast({
          title: "配送成功",
          icon: "success",
        });
      }
    },
    //送达
    async handleFinishSendingOrder() {
      const orderNo = this.orderData?.orderNo;
      const res = await orderDelivered({ orderNo: orderNo }).catch((err) => {
        uni.showToast({
          title: err.msg,
          icon: "none",
        });
      });
      await this.fetchOrderDetail();
      if (res?.code === 0) {
        uni.showToast({
          title: "成功",
          icon: "success",
        });
      }
    },
  },
};
</script>
<style>
page {
  background-color: #f7f7f7;
}
</style>
<style lang="scss" scoped>
.page {
  padding: 20rpx;
  box-sizing: border-box;
}
.store {
  background-color: white;
  padding: 30rpx 26rpx;
  box-sizing: border-box;
  border-radius: 8rpx;
  font-size: 29rpx;
  font-weight: 500;
  color: #131313;
  .addres {
    margin-top: 24rpx;
    opacity: 0.7;
  }
}
.merch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 30rpx 26rpx;
  box-sizing: border-box;
  margin-top: 20rpx;
  border-radius: 8rpx;
  .rig {
    .top {
      display: flex;
      justify-items: flex-start;
      .indus {
        font-size: 22rpx;
        color: #a68453;
        background: #feda95;
        border-radius: 8rpx;
        padding: 7rpx 13rpx;
        box-sizing: border-box;
      }
    }
    .btm {
      font-size: 24rpx;
      color: #131313;
      opacity: 0.7;
      margin-top: 20rpx;
    }
  }
  .lef {
    font-size: 27rpx;
    color: #a1a1a0;
    font-weight: 500;
    text-align: center;
    .cause {
      font-size: 22rpx;
    }
  }
}
.user-info {
  background-color: white;
  padding: 30rpx 26rpx;
  box-sizing: border-box;
  margin-top: 20rpx;
  border-radius: 8rpx 8rpx 0 0;

  .place-order,
  .rec-order {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 29rpx;
    font-weight: 500;
    color: #131313;
    //border-top: 1rpx solid #ececec;
    text {
      margin-left: 42rpx;
      color: #131313;
      opacity: 0.8;
    }
    .phone {
      background-color: #ffb72f;
      border-radius: 50%;
      overflow: hidden;
      width: 49rpx;
      height: 49rpx;
      text-align: center;
      line-height: 49rpx;
      .iconfont {
        color: white;
      }
    }
  }
  .place-order {
    padding-bottom: 30rpx;
  }
  .rec-order {
    border-top: 1rpx solid #ececec;
    padding-top: 30rpx;
    padding-bottom: 30rpx;
    .row {
      margin-top: 23rpx;
    }
    .remarks {
      color: #131313;
      opacity: 0.7;
    }
  }
  .userRemark {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #131313;
    opacity: 0.7;
    //padding: 28rpx 0;
  }
}
.shop-info {
  background-color: white;
  padding: 0 0 30rpx 26rpx;
  box-sizing: border-box;
  border-radius: 0 0 8rpx 8rpx;

  .shop-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    padding-right: 16rpx;
    box-sizing: border-box;
    .lef {
      display: flex;
      justify-items: flex-start;
      align-items: center;
      flex: 1;
      .img {
        width: 150rpx;
        height: 150rpx;
        background-color: #f5f5f5;
        margin-right: 21rpx;
        image {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .name {
        font-size: 29rpx;
        font-weight: bold;
        color: #181818;
      }
      .spec {
        font-size: 27rpx;
        font-weight: 500;
        color: #888888;
        margin-top: 8rpx;
      }
    }
    .rig {
      font-weight: 500;
      text-align: right;
      .num {
        font-size: 29rpx;
        font-weight: 500;
        color: #888888;
      }
      .price {
        font-size: 24rpx;
        color: #f05357;
        .bigPrice {
          font-size: 36rpx;
        }
      }
    }
  }
}
.amount-info,
.order-info {
  background-color: white;
  padding: 30rpx 26rpx;
  box-sizing: border-box;
  margin-top: 20rpx;
  border-radius: 8rpx;
  .row {
    display: flex;
    justify-content: space-between;
    font-size: 29rpx;
    font-weight: 500;
    color: #131313;
    margin-top: 31rpx;
    .tit {
      opacity: 0.7;
    }
    .yh {
      text-align: right;
      font-size: 26rpx;
    }
  }
  .row:nth-of-type(1) {
    margin: 0;
  }
}
.order-info {
  margin-bottom: 180rpx;
}
.oper-info {
  position: fixed;
  bottom: 0;
  background-color: white;
  width: 100%;
  left: 0;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  padding: 25rpx 32rpx;
  padding-bottom: calc(constant(safe-area-inset-bottom) + 25rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 25rpx);
  box-sizing: border-box;
  .amount {
    display: flex;
    justify-content: space-between;
    font-size: 32rpx;
    .money {
      font-size: 24rpx;
      color: #f05357;
      text {
        font-size: 32rpx;
      }
    }
  }
  .print {
    text-align: center;
    font-size: 24rpx;
    color: #ffb72f;
    .iconfont {
      font-size: 46rpx;
    }
  }
}
.operBtn {
  margin-left: 20rpx;
}
.blank-box {
  width: 686rpx;
  height: 100rpx;
}
</style>
